#include <stdio.h>
#include <unistd.h>

#include "hi_wifi_api.h"
#include "lwip/ip_addr.h"
#include "lwip/netifapi.h"
#include "lwip/sockets.h"
#include "MQTTPacket.h"
#include "transport.h"
#include "environment_task.h"

int mqtt_connect(void){
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    int mysock = 0;
    unsigned char buf[200];
    int buflen = sizeof(buf);

    MQTTString topicString = MQTTString_initializer;
    char payload[200];
    int payloadlen = strlen(payload);
    int len = 0;

    char *host = "192.168.43.6";
    int port = 1883;
    topicString.cstring = "ems";

    data.clientID.cstring = "hi3861_lpz";
    data.keepAliveInterval = 20;
    data.cleansession = 1;
    data.username.cstring = "hi3861_ems";
    data.password.cstring = "testpassword";

    mysock = transport_open(host,port);
    if(mysock<0){
        printf("mysock failed\n");
        return mysock;
    }
    printf("sending to hostname %s port %d by lpz\n",host,port);

    len = MQTTSerialize_connect(buf,buflen,&data);
    transport_sendPacketBuffer(mysock,buf,len);
    if (MQTTPacket_read(buf,buflen,transport_getdata)==CONNACK)
    {
        printf("communication...1\n");
        unsigned char sessionPresent,connack_rc;
        if (MQTTDeserialize_connack(&sessionPresent,&connack_rc,buf,buflen)!=1|| connack_rc!=0)
        {
            printf("Unable to connect,return code %d\n",connack_rc);
            goto exit;
        }    
    }else{
        goto exit;
    }

    while (1==1)
    {
        printf("communication...loop\n");
        snprintf(payload,sizeof(payload),"{\"stat\":%d,\"gas\":%d,\"temp\":%.1f,\"hum\":%.1f}",
        stat,gas,temperature,humidity);
        payloadlen = strlen(payload);
        len = MQTTSerialize_publish(buf,buflen,0,0,0,0,topicString,(unsigned char*)payload,payloadlen);
        transport_sendPacketBuffer(mysock,buf,len);
        sleep(1);
    }
    exit:
        transport_close(mysock);
        return 0;
    
}